//
//  ChatBoxComponent.m
//  XYLib
//
//  Created by Richard on 2019/3/4.
//  Copyright © 2019年 XY. All rights reserved.
//
#import "ChatBoxComponent.h"
#import "UIView+Extension.h"
#import "NSString+CODEC.h"
#import "NSAttributedString+Emoji.h"
#import "WXConvert.h"
#import "WXUtility.h"
#import "Emotion.h"
#import "UITextView+Placeholder.h"
#import "ICChatServerDefs.h"
#import "UIColor+IGColor.h"
#import "EmojiTextAttachment.h"

#define textViewFont 16.0f

//匹配以@开头空格结尾的字符串
//#define kATRegular @"@\\w+\\s"
//匹配以@开头空格结尾的字符串
#define kATRegular @"\\{\\@(.*?)\\}"
#define ATColor (@"#0d81ff")

#define AT_REG_Before   @"\\{\\@(.*?)\\}"
#define AT_REG_After   @"\\s\\@(.*?)\\s"

@interface ChatBoxComponent()<UITextViewDelegate>

/** 保存状态 */
@property (nonatomic, assign) ICChatBoxStatus status;

/** 输入框 */
@property (nonatomic, strong) UITextView *textView;

@property (nonatomic, assign) NSInteger currentLine;
@property (nonatomic, assign) CGFloat originalHeight;
@property (nonatomic, assign) CGFloat originalLineHeight;

@end

@implementation ChatBoxComponent
- (instancetype)initWithRef:(NSString *)ref type:(NSString *)type styles:(NSDictionary *)styles attributes:(NSDictionary *)attributes events:(NSArray *)events weexInstance:(WXSDKInstance *)weexInstance {
    self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance];
    if (self) {
        _placeholderString = [WXConvert NSString:attributes[@"placeholder"]]?:@"";
        _disabled = [WXConvert BOOL:attributes[@"disabled"]];
        _keyboardShow = [WXConvert BOOL:attributes[@"keyboardShow"]];
        _marginTop = [WXConvert CGFloat:attributes[@"marginTop"]]/2?:0;
        _marginBottom = [WXConvert CGFloat:attributes[@"marginBottom"]]/2?:0;
        _maxLineNum = [WXConvert CGFloat:attributes[@"maxLineNum"]]?:3;
        _maxLength = [WXConvert CGFloat:attributes[@"maxLength"]]?:500;
        _textColor = [UIColor colorWithStr:[WXConvert NSString:attributes[@"textColor"]]?:@""];
        _placeholderColor = [UIColor colorWithStr:[WXConvert NSString:attributes[@"placeholderColor"]]?:@""];

        if (attributes[@"atTextColor"]) {
            _atTextColor = [UIColor colorWithStr:[WXConvert NSString:attributes[@"atTextColor"]]];
        }else{
            _atTextColor = [UIColor colorWithStr:ATColor];
        }
        
        if (styles[@"fontSize"]) {
            _fontSize = [WXConvert CGFloat:styles[@"fontSize"]] * self.weexInstance.pixelScaleFactor;
        } else {
            _fontSize = textViewFont;
        }
    }
    return self;
}

- (UITextView *) textView
{
    if (_textView == nil) {
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        [_textView setFont:[UIFont systemFontOfSize:_fontSize]];
        [_textView.layer setMasksToBounds:YES];
        [_textView setScrollsToTop:NO];
        [_textView setReturnKeyType:UIReturnKeyDone];
        [_textView setDelegate:self];
        
        CGFloat padding = _textView.textContainer.lineFragmentPadding;
        _textView.textContainerInset = UIEdgeInsetsMake(0, -padding, 0, -padding);
        
        _textView.backgroundColor = [UIColor clearColor];
        _textView.textColor = _textColor;
        
        if(_textView.font.lineHeight <= _textView.frame.size.height) {
            CGFloat offsetY = (_textView.frame.size.height - _textView.font.lineHeight)/2;
            UIEdgeInsets offset = UIEdgeInsetsMake(offsetY, 0, 0, 0);
            [_textView setContentInset:offset];
        }

        self.currentLine = 1;
        self.originalHeight = _textView.frame.size.height;
        self.originalLineHeight = _textView.font.lineHeight;
        
        //        _textView.text = @" ";
        
        _textView.placeholder = _placeholderString;
        _textView.placeholderColor = _placeholderColor;
        _textView.placeholderLabel.font = [UIFont systemFontOfSize:_fontSize];
        [_textView setEditable:!_disabled];
    }
    return _textView;
}

-(void)viewDidLoad
{
    [self.view addSubview:self.textView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

// 键盘出现 事件
- (void) keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
//    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
//    //计算出键盘顶端到inputTextView 底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
//    CGFloat offset = kbHeight - (self.view.frame.size.height -self.textView.frame.origin.y - self.textView.frame.size.height);
//
//    [self fireEvent:@"keyboard" params:@{@"height": [NSNumber numberWithFloat:offset * 2]}];

    
    CGRect end = [[[notification userInfo] objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
   
    [self fireEvent:@"keyboard" params:@{@"height": @(end.size.height / self.weexInstance.pixelScaleFactor)}];

}

// 键盘消失 事件
- (void) keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
//    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [self fireEvent:@"keyboard" params:@{@"height": [NSNumber numberWithFloat:0]}];
}

- (void)updateAttributes:(NSDictionary *)attributes
{
    if (attributes[@"placeholder"]) {
        _placeholderString = [WXConvert NSString:attributes[@"placeholder"]];
        _textView.placeholder = _placeholderString;
    }
    
    if (attributes[@"value"]) {
        NSString *str = [WXConvert NSString:attributes[@"value"]];
        // 发送信息后，将输入内容置为空
        if ([str isEqualToString:@""]) {
            self.textView.text = str;
            NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
            self.textView.attributedText = string;
            self.textView.frame = CGRectMake(0, 0, self.textView.frame.size.width, self.originalHeight);
            self.currentLine = 1;
        }

        // 表情
        if([str rangeOfString:@"face_text"].length > 0 && [str rangeOfString:@"face_name"].length > 0 && [str rangeOfString:@"face_id"].length > 0  && [self countTextStorageLength] < _maxLength){
            str = [NSString stringWithFormat:@"[%@]",str];
            NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil][0];
            if ([[dic objectForKey:@"face_name"] isEqualToString:@"delete"]) {
                [self deleteBtnClicked];
            }else{
                Emotion *model = [[Emotion alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self setTextEmoji:model];
            }
        }
        // TO DO @ 文本  如 {@助理}
        NSPredicate *pred_box = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", AT_REG_Before];
        if ([pred_box evaluateWithObject:str] && ([self countTextStorageLength] + [str length] <= _maxLength)){
            [self setTextRemind:str];
        }
        // TO DO 普通文本
        else {
            
        }

        if ([self countTextStorageLength] > 0) {
            _textView.placeholderLabel.hidden = YES;
        } else{
            _textView.placeholderLabel.hidden = NO;
        }

        NSString *strMix = [self.textView.textStorage getPlainString];
        [self fireEvent:@"input" params:@{@"value":strMix}];
        
    }
    if (attributes[@"disabled"]) {
        _disabled = [WXConvert BOOL:attributes[@"disabled"]];
        [_textView setEditable:!_disabled];
        
    }
    if (attributes[@"keyboardShow"]) {
        _keyboardShow = [WXConvert BOOL:attributes[@"keyboardShow"]];
        if (!_keyboardShow) {
            [self.view endEditing:YES];
            [self.textView resignFirstResponder];
        }
        
    }
    if (attributes[@"marginTop"]) {
        _marginTop = [WXConvert CGFloat:attributes[@"marginTop"]]/2;
    }
    if (attributes[@"marginBottom"]) {
        _marginBottom = [WXConvert CGFloat:attributes[@"marginBottom"]]/2;
    }
    if (attributes[@"maxLineNum"]) {
        _maxLineNum = [WXConvert CGFloat:attributes[@"maxLineNum"]];
    }
    if (attributes[@"textColor"]) {
        _textColor = [UIColor colorWithStr:[WXConvert NSString:attributes[@"textColor"]]?:@""];
        _textView.textColor = _textColor;
    }
    if (attributes[@"placeholderColor"]) {
        _placeholderColor = [UIColor colorWithStr:[WXConvert NSString:attributes[@"placeholderColor"]]?:@""];
        _textView.placeholderColor = _placeholderColor;
    }
    if (attributes[@"atTextColor"]) {
        _atTextColor = [UIColor colorWithStr:[WXConvert NSString:attributes[@"atTextColor"]]?:@""];
    }
    if (attributes[@"maxLength"]) {
        _maxLength = [WXConvert CGFloat:attributes[@"maxLength"]];
    }
//
//    if (attributes[@"disableMoveViewUp"]) {
//        _disableMoveViewUp = [WXConvert BOOL:attributes[@"disableMoveViewUp"]];
//    }
//    if (attributes[@"value"]) {
//        _value = [WXConvert NSString:attributes[@"value"]]?:@"";
//        if (_maxLength && [_value length] > [_maxLength integerValue]&& [_maxLength integerValue] >= 0) {
//            _value = [_value substringToIndex:([_maxLength integerValue])];
//        }
//        [self setText:_value];
//    }
//    if (attributes[@"placeholder"]) {
//        _placeholderString = [WXConvert NSString:attributes[@"placeholder"]]?:@"";
//        [self setPlaceholderAttributedString];
//        if(_value.length > 0){
//            _placeHolderLabel.text = @"";
//        }
//    }
//    if (attributes[@"returnKeyType"]) {
//        _returnKeyType = [WXConvert UIReturnKeyType:attributes[@"returnKeyType"]];
//        [self setReturnKeyType:_returnKeyType];
//    }
//    if (attributes[@"rows"]) {
//        _rows = [attributes[@"rows"] integerValue];
//        [self setRows:_rows];
//    } else {
//        _rows = 2;
//        [self setRows:_rows];
//    }
}
#pragma mark - UITextViewDelegat
- (void) textViewDidBeginEditing:(UITextView *)textView
{
    self.status = ICChatBoxStatusShowKeyboard;
//    if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
//        [_delegate chatBox:self changeStatusForm:self.status to:self.status];
//    }
    
}

- (void) textViewDidChange:(UITextView *)textView
{
    if ([self countTextStorageLength] > _maxLength) {
        for (int i = 0; i < [self countTextStorageLength] - _maxLength; i++) {
            [self deleteBtnClicked];
        }
        return;
    }
    
    UITextRange *selectedRange = textView.markedTextRange;
    NSString *newText = [textView textInRange:selectedRange];
    if (newText.length < 1)
    {
        // 高亮输入框中的@
        NSRange range = textView.selectedRange;

        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
        [string addAttribute:NSForegroundColorAttributeName value:_textColor range:NSMakeRange(0, string.string.length)];

        NSArray *matches = [self findAllAt];

        for (NSTextCheckingResult *match in matches)
        {
            [string addAttribute:NSForegroundColorAttributeName value:_atTextColor range:NSMakeRange(match.range.location, match.range.length - 1)];
        }

        [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:_fontSize] range:NSMakeRange(0, string.length)];
        textView.attributedText = string;
        textView.selectedRange = range;
    }
    
    NSString *strMix = [self.textView.textStorage getPlainString];
    [self fireEvent:@"input" params:@{@"value":strMix}];
    
//    if (strMix.length<=0) {
//        [textView setFrame:CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, self.originalHeight)];
//        CGFloat weex_height = self.originalHeight * 2 + _marginTop + _marginBottom;
//        [self fireEvent:@"inputHeight" params:@{@"height": [NSNumber numberWithFloat:weex_height]}];
//    }
    [self countHeightForTextView:textView];
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    
    [textView scrollRangeToVisible:textView.selectedRange];
    
    // 光标不能点落在@词中间
    NSRange range = textView.selectedRange;
    if (range.length > 0)
    {
        // 选择文本时可以
        return;
    }
    
    NSArray *matches = [self findAllAt];
    for (NSTextCheckingResult *match in matches)
    {
        NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
        if (NSLocationInRange(range.location, newRange))
        {
            textView.selectedRange = NSMakeRange(match.range.location + match.range.length, 0);
            break;
        }
    }
}

//textview的send按钮事件
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //回车，发送字符
    if ([text isEqualToString:@"\n"]){
        [self.textView resignFirstResponder];
        return NO;
    }
    
    //删除键盘
    if ([text isEqualToString:@""]){
        NSRange selectRange = textView.selectedRange;
        if (selectRange.length > 0)
        {
            //用户长按选择文本时不处理
            return YES;
        }
        
        NSArray *matches = [self findAllAt];
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
        BOOL inAt = NO;
        NSInteger index = range.location;
        for (NSTextCheckingResult *match in matches)
        {
            NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
            if (NSLocationInRange(range.location, newRange))
            {
                inAt = YES;
                index = match.range.location;
                [attrStr removeAttribute:NSForegroundColorAttributeName range:match.range];
                [attrStr replaceCharactersInRange:match.range withString:@""];
                break;
            }
        }
        
        if (inAt)
        {
            textView.attributedText = attrStr;
            textView.selectedRange = NSMakeRange(index, 0);
            
            NSString *strMix = textView.attributedText.string;
            [self fireEvent:@"input" params:@{@"value":strMix}];
            [self countHeightForTextView:textView];
            return NO;
        }
    }

    return YES;
}

- (void)countHeightForTextView:(UITextView *)textView
{
    //    if([_textView.text hasPrefix:@" "]){
    //        _textView.text=[_textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    //    }
    
    int maxLineNum = _maxLineNum;
    CGFloat textViewHeight = textView.frame.size.height;

    CGSize newSize = textView.textStorage.size;

    int line = ceil(newSize.width / textView.frame.size.width);
    if (line < 1) {
        line = 1;
    }

    self.currentLine = MIN(line, maxLineNum);

    NSInteger height = self.originalHeight+ (self.currentLine - 1)  * self.originalLineHeight;
    if (height < textView.contentSize.height && self.currentLine < maxLineNum) {
        height = textView.contentSize.height;
    }
    if (height != CGRectGetHeight(self.textView.bounds)) {
        [textView setFrame:CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, height)];
        CGFloat weex_height = height * 2 + _marginTop + _marginBottom;
        [self fireEvent:@"inputHeight" params:@{@"height": [NSNumber numberWithFloat:weex_height]}];
//        [textView setContentSize:textView.size];
    }
    
    [textView scrollRangeToVisible:textView.selectedRange];
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(EmojiTextAttachment *)textAttachment inRange:(NSRange)characterRange{
    // 解决14.0~14.1系统,点击输入内容以表情结尾的空白区域，输入框无法聚焦的问题
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 14.0 && [[UIDevice currentDevice].systemVersion floatValue] < 14.2) {
        self.textView.selectedRange = NSMakeRange(characterRange.location + characterRange.length, 0);
        [self.textView becomeFirstResponder];
    }
    //禁用图片的长按事件
    if (![NSString isBlankString:textAttachment.emojiTag]) {
        return NO;
    }
    return YES;
}
-(void)sendTheMessageByKeyBoardOrFoceView:(BOOL )isNotice
{
    NSString *plainString = [self.textView.textStorage getPlainString];
    plainString= [plainString stringByReplacingOccurrencesOfString:kATRegular withString:@"{$0} " options:NSRegularExpressionSearch range:NSMakeRange(0, plainString.length)];
    plainString = [plainString stringByReplacingOccurrencesOfString:@" } " withString:@"} "];
//    if (_delegate && [_delegate respondsToSelector:@selector(chatBox:sendTextMessage:isNotice:)]) {
//        [_delegate chatBox:self sendTextMessage:plainString isNotice:isNotice];
//    }
}

- (NSArray<NSTextCheckingResult *> *)findAllAt
{
//    NSString *str = @"{@助理}";
//    NSString *partten = @"\\{\\@(.*?)\\}";
    
    // 找到文本中所有的@
    NSString *string = self.textView.textStorage.string;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:AT_REG_After options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regex matchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
    return matches;
}

//重置text的style
- (void)resetTextStyle {
    //After changing text selection, should reset style.
    NSRange wholeRange = NSMakeRange(0, _textView.textStorage.length);
    [_textView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
    [_textView.textStorage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:_fontSize] range:wholeRange];
}

- (NSString *)createMessage{
    NSString *plainString = [self.textView.textStorage getPlainString];
    plainString= [plainString stringByReplacingOccurrencesOfString:kATRegular withString:@"{$0} " options:NSRegularExpressionSearch range:NSMakeRange(0, plainString.length)];
    plainString = [plainString stringByReplacingOccurrencesOfString:@" } " withString:@"} "];
    return plainString;
}

-(void)setTextRemind:(NSString *)str
{
    NSRange range = self.textView.selectedRange;
    
    NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:AT_REG_Before options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regular matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:str];
    for (NSTextCheckingResult *match in matches)
    {
        [string addAttribute:NSForegroundColorAttributeName value:_atTextColor range:NSMakeRange(match.range.location, match.range.length)];
        [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:_fontSize] range:NSMakeRange(match.range.location, string.length)];

        [string replaceCharactersInRange:NSMakeRange(match.range.length -1, 1) withString:@" "];
        [string replaceCharactersInRange:NSMakeRange(match.range.location, 1) withString:@" "];
//        [string deleteCharactersInRange: NSMakeRange(match.range.length -1, 1)];
//        [string deleteCharactersInRange: NSMakeRange(match.range.location, 1)];
        
//        if (![self.textView.textStorage.string containsString:string.string]) {
//            [self.textView.textStorage appendAttributedString:string];
            [self.textView.textStorage insertAttributedString:string atIndex:range.location];
            self.textView.selectedRange = NSMakeRange(match.range.location + match.range.length + range.location, 0);
        
        [self countHeightForTextView:self.textView];
//        }
    }

}

-(void)setTextEmoji:(Emotion *)emoji
{
    //Create emoji attachment
    EmojiTextAttachment *emojiTextAttachment = [EmojiTextAttachment new];
    //Set tag and image
    emojiTextAttachment.emojiTag = emoji.face_text;
    emojiTextAttachment.image = [UIImage imageNamed:emoji.face_name];
    //Set emoji size
    
    emojiTextAttachment.emojiSize = CGSizeMake(self.originalLineHeight, self.originalLineHeight);
    
    NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:emojiTextAttachment];
    NSRange selectedRange = self.textView.selectedRange;
    if (selectedRange.length > 0) {
        [self.textView.textStorage deleteCharactersInRange:selectedRange];
    }
    
    //Insert emoji image
    [self.textView.textStorage insertAttributedString:str atIndex:self.textView.selectedRange.location];
    self.textView.selectedRange = NSMakeRange(self.textView.selectedRange.location+1, 0); //
    
    [self countHeightForTextView:self.textView];
    
    //Reset text style
    [self resetTextStyle];
}
#pragma mark - Private
//选择表情的通知方法
- (void)emotionDidSelected:(NSNotification *)notifi
{
//    XZEmotion *emotion = notifi.userInfo[GXSelectEmotionKey];
//    if (emotion.face_name) {
//        [self setTextEmoji:emotion];
//        if (self.textView.placeholderLabel.superview) {
//            [self.textView.placeholderLabel removeFromSuperview];
//        }
//    } else if (emotion.code) {
//        [self.textView insertText:emotion.code.emoji];
//        [self.textView scrollRangeToVisible:NSMakeRange(self.textView.text.length, 0)];
//    }
}

// 删除表情的通知方法
- (void)deleteBtnClicked
{
    [self.textView deleteBackward];
}

// 发送表情的通知方法
- (void)sendMessage
{
    [self.textView setText:@""];
}

- (void)contentSizeToFit:(UITextView *)answerTextView {
//    if([answerTextView.text length]>0) {
        CGSize contentSize = answerTextView.contentSize;
        //NSLog(@"w:%f h%f",contentSize.width,contentSize.height);
        UIEdgeInsets offset;
        CGSize newSize = contentSize;
        if(contentSize.height <= answerTextView.frame.size.height) {
            CGFloat offsetY = (answerTextView.frame.size.height - contentSize.height)/2;
            offset = UIEdgeInsetsMake(offsetY, 0, offsetY, 0);
            
        }
        else {
            newSize = answerTextView.frame.size;
            offset = UIEdgeInsetsZero;
            CGFloat fontSize = _fontSize;
            while (contentSize.height > answerTextView.frame.size.height) {
                [answerTextView setFont:[UIFont fontWithName:@"Helvetica Neue" size:fontSize--]];
                contentSize = answerTextView.contentSize;
            }
            newSize = contentSize;
        }
        [answerTextView setContentSize:newSize];
        [answerTextView setContentInset:offset];
//    }
}

- (void)countHeightForTextView:(UITextView *)textView newText:(NSString *)newText
{
    int maxLineNum = _maxLineNum;
    CGFloat textViewHeight = textView.frame.size.height;
    CGFloat maxHeight = ceil(textView.font.lineHeight * maxLineNum +  textView.textContainerInset.top + textView.textContainerInset.bottom);
    
    CGSize newSize = [newText boundingRectWithSize:CGSizeMake(textView.frame.size.width, MAXFLOAT)
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                        attributes:@{NSFontAttributeName: textView.font}
                                           context:nil].size;
    
    //    if (emojiTextAttachment) {
    //        if (newSize.width + emojiTextAttachment.emojiSize.width < textView.frame.size.width) {
    //            newSize.width = newSize.width + emojiTextAttachment.emojiSize.width;
    //        }else{
    //            newSize.height = newSize.height + emojiTextAttachment.emojiSize.height;
    //        }
    //    }
    
    int line = ceil(newSize.height / textView.font.lineHeight);
    
    self.currentLine = MIN(line, maxLineNum);
    NSInteger height = self.originalHeight+ (self.currentLine -1 )  * textView.font.lineHeight;
    if (height != CGRectGetHeight(self.textView.bounds)) {
        [textView setFrame:CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, height)];
        CGFloat weex_height = height * 2 + _marginTop + _marginBottom;
        [self fireEvent:@"inputHeight" params:@{@"height": [NSNumber numberWithFloat:weex_height]}];
    }
    
}

- (CGFloat)countTextStorageLength{
    NSMutableString *text = [NSMutableString stringWithString:[self.textView.textStorage getPlainString]];

    // 表情
    NSString *pattern = @"\\:(.*?)\\:";
    NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regular matchesInString:text options:0 range:NSMakeRange(0, text.length)];
    
    for (long i = matches.count - 1; i >= 0; i--) {
        NSTextCheckingResult *match = matches[i];
        [text replaceCharactersInRange:NSMakeRange(match.range.location, match.range.length) withString:@"T"];
    }
    return text.length;
}
@end
